package com.ruoyi.web.controller.wx_driver;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.vqms.domain.*;
import com.ruoyi.vqms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wx/yuchai")
public class VisitRecordYuchaiController extends BaseController {

    @Autowired
    private IVQMSVisitRecordYuchaiService visitRecordYuchaiService;
    @Autowired
    private IVQMSVisitRecordYuchiService visitRecordYuchiService;
    @Autowired
    private IVQMSQueueReservationService queueReservationService;
    @Autowired
    private IVQMSQueueService queueService;
    @Autowired
    private IVQMSQueueAreaService queueAreaService;
    @Autowired
    private IVQMSDriverService driverService;
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    IVQMSLedService ledService;


    /**
     * 司机查询访客记录（不分页）
     *
     * @param vqmsVisitRecordYuchai
     * @return
     */
    @RequestMapping("/list")
    public AjaxResult list(VQMSVisitRecordYuchai vqmsVisitRecordYuchai) {
        List<VQMSVisitRecordYuchai> list = visitRecordYuchaiService.wxSelectList(vqmsVisitRecordYuchai);
        return AjaxResult.success(list);
    }

    /**
     * 新增访问记录（玉柴）
     */
    @Log(title = "新增访问记录（玉柴）", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody VQMSVisitRecordYuchai vqmsVisitRecordYuchai) {
        if (vqmsVisitRecordYuchai.getLicensePlate().equals("无")){
            vqmsVisitRecordYuchai.setLicensePlate(null);
        }
        // 如果没有访客（司机），则新增。否则更新访客（司机）
        VQMSDriver old = driverService.getByPhone(vqmsVisitRecordYuchai.getPhone());
        if (old == null) {
            VQMSDriver vqmsDriver = new VQMSDriver();
            vqmsDriver.setName(vqmsVisitRecordYuchai.getDriverName());
            vqmsDriver.setPhone(vqmsVisitRecordYuchai.getPhone());
            vqmsDriver.setLicensePlate(vqmsVisitRecordYuchai.getLicensePlate());
            vqmsDriver.setCreateBy(vqmsVisitRecordYuchai.getDriverName());
            driverService.add(vqmsDriver);
            //新增之后重新查询，排除id为空的情况
            vqmsDriver = driverService.getByPhone(vqmsVisitRecordYuchai.getPhone());
            vqmsVisitRecordYuchai.setDriverId(vqmsDriver.getId());
        } else {
            //查询上一条是否确认
            VQMSVisitRecordYuchai visitRecordYuchai = visitRecordYuchaiService.getYuchaiFactoryTime(vqmsVisitRecordYuchai.getPhone());
            if (visitRecordYuchai != null) {
                visitRecordYuchai.setRegistrationStatus(2);
                visitRecordYuchai.setConfirmedBy(2);
                visitRecordYuchai.setConfirmedTime(new Date());
                int i = visitRecordYuchaiService.update(visitRecordYuchai); //完成上一条
//                return AjaxResult.error("上条预约记录未确认");
            }

            old.setName(vqmsVisitRecordYuchai.getDriverName());
            old.setPhone(vqmsVisitRecordYuchai.getPhone());
            old.setLicensePlate(vqmsVisitRecordYuchai.getLicensePlate());
            old.setUpdateBy(vqmsVisitRecordYuchai.getDriverName());
            driverService.update(old);
            vqmsVisitRecordYuchai.setDriverId(old.getId());

        }
        vqmsVisitRecordYuchai.setFactoryId((long) 11);   //默认玉柴id
        vqmsVisitRecordYuchai.setRegistrationStatus(2);     //默认已确认
        vqmsVisitRecordYuchai.setConfirmedBy(1);        //确认人  1：本人确认
        vqmsVisitRecordYuchai.setConfirmedTime(new Date());     //确认时间
        vqmsVisitRecordYuchai.setCreateBy(vqmsVisitRecordYuchai.getDriverName());
        visitRecordYuchaiService.add(vqmsVisitRecordYuchai);
        return AjaxResult.success();
    }

    /**
     * 查询最近的一条南大门或者中心仓库的记录
     */
    @GetMapping("/getReservation/{phone}")
    public AjaxResult getReservation(@PathVariable String phone) {
        //查询当天是否有预约未确认记录
//        VQMSVisitRecordYuchai vqmsVisitRecordYuchai = visitRecordYuchaiService.getYuchaiFactoryTime(phone);
        VQMSVisitRecordYuchai vqmsVisitRecordYuchai = new VQMSVisitRecordYuchai();
        vqmsVisitRecordYuchai.setPhone(phone);
        List<VQMSVisitRecordYuchai> list = visitRecordYuchaiService.getLatestCreateTime(vqmsVisitRecordYuchai);
        if (list.isEmpty()){
            return AjaxResult.success("201", null);
        }
        return AjaxResult.success("200",list.get(0));
    }

    /**
     * 根据id查询对应预约记录
     */
    @GetMapping("/getIdReservation/{id}")
    public AjaxResult getIdReservation(@PathVariable Long id) {
        //查询当天是否有预约未确认记录
        VQMSVisitRecordYuchai vqmsVisitRecordYuchai = visitRecordYuchaiService.getById(id);
        if (vqmsVisitRecordYuchai == null) {
            return AjaxResult.error("未找到对应预约记录");
        }
        return AjaxResult.success(vqmsVisitRecordYuchai);
    }

    /**
     * 司机确认预约(玉柴)
     *
     * @param vqmsVisitRecordYuchai
     * @return
     */
    @Log(title = "司机登记确认(玉柴)", businessType = BusinessType.INSERT)
    @PostMapping("/confirm")
    public AjaxResult confirm(@RequestBody VQMSVisitRecordYuchai vqmsVisitRecordYuchai) {
        //查询是否有记录
        VQMSVisitRecordYuchai visitRecordYuchai = visitRecordYuchaiService.getById(vqmsVisitRecordYuchai.getId());
        String name = SecurityUtils.getUsername();
        if (visitRecordYuchai == null) {
            return AjaxResult.error("未找到预约记录");
        }
        visitRecordYuchai.setRegistrationStatus(2);     //已确认
        visitRecordYuchai.setConfirmedBy(1);            //本人确认
        visitRecordYuchai.setConfirmedTime(new Date()); //确认时间
        if (SecurityUtils.getUsername() != null){
            visitRecordYuchai.setUpdateBy(SecurityUtils.getUsername()); //修改人
            visitRecordYuchai.setUpdateTime(new Date());
        }
        visitRecordYuchai.setUpdateBy(name);
        int reservationStatus = 0;     //预约状态

        if (visitRecordYuchai.getReservationId() != null) {  //预约id不为空，需要生成排队任务，同时确认玉驰对应记录
            //确认玉驰访客记录
            VQMSVisitRecordYuchi visitRecordYuchi = new VQMSVisitRecordYuchi();
            visitRecordYuchi.setReservationId(visitRecordYuchai.getReservationId());
            List<VQMSVisitRecordYuchi> yuchiList = visitRecordYuchiService.selectList(visitRecordYuchi);
            if (yuchiList.isEmpty() || yuchiList.get(0) == null) {
//                return AjaxResult.error("同步访客记录-未找到玉驰预约记录");
                logger.error("同步访客记录-未找到玉驰预约记录");
            }
            // 4. 获取并更新玉驰记录
            VQMSVisitRecordYuchi yuchiRecord = yuchiList.get(0);
            yuchiRecord.setRegistrationStatus(2); // 已确认
            yuchiRecord.setConfirmedBy(1);          //本人确认
            yuchiRecord.setConfirmedTime(new Date());   //确认时间
            if (SecurityUtils.getUsername() != null){
                yuchiRecord.setUpdateBy(SecurityUtils.getUsername()); //修改人
                yuchiRecord.setUpdateTime(new Date());
            }

            // 5. 执行更新并检查结果
            int updateSuccess = visitRecordYuchiService.update(yuchiRecord);
            if (updateSuccess != 1) {
//                return AjaxResult.error("同步访客记录-更新玉驰记录失败");
                logger.error("同步访客记录-更新玉驰记录失败");
            }

            //生成排队记录
            //生成排队信息
            VQMSQueueReservation vqmsQueueReservation = queueReservationService.getById(visitRecordYuchai.getReservationId());
            int i = queueService.wxAdd(vqmsQueueReservation);
            //发送模板消息
            if (i == 1) {        //新增排队任务成功
                reservationStatus = 2;     //已确认
                //查询对应排队任务获取信息
                VQMSQueue vqmsQueue = new VQMSQueue();
                vqmsQueue.setReservationId(vqmsQueueReservation.getId());
                List<VQMSQueue> list = queueService.selectList(vqmsQueue);
                if (list.isEmpty()) {
                    logger.error("确认玉柴登记发送提醒消息-未找到排队任务");
//                    return AjaxResult.error("发送提醒消息-未找到排队任务");
                }
                VQMSQueueArea vqmsQueueArea = queueAreaService.getById(list.get(0).getAreaId());
                String wxOpenId = vqmsQueueReservation.getWxOpenId();
                String reservationId = String.valueOf(list.get(0).getReservationId());  //签到编号
                String status = "已叫号";
                String areaName = vqmsQueueArea.getName().replace("队列", "");      //月台编号
                String driverName = vqmsQueueReservation.getDriverName();               //司机姓名
                String licensePlate = vqmsQueueReservation.getLicensePlate();           //车牌号
                sendMsgService.send_msg(wxOpenId, reservationId, status, areaName, driverName, licensePlate);
                //刷新LED大屏
                try {
                    ledService.flushLesScreenData(vqmsQueueArea.getId());
                } catch (Exception e) {
                    logger.error("司机新增排队刷新LED大屏失败");
                    e.printStackTrace();
                }
            } else {        //新增排队任务失败，直接完成预约任务
                reservationStatus = 3;     //已完成
            }
            vqmsQueueReservation.setStatus(reservationStatus);
            int m = queueReservationService.update(vqmsQueueReservation);   //更改预约状态

        }
        return AjaxResult.success(visitRecordYuchaiService.update(visitRecordYuchai));
    }

    /**
     * 司机出厂登记(扫二维码)
     *
     * @param vqmsVisitRecordYuchai
     * @return
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody VQMSVisitRecordYuchai vqmsVisitRecordYuchai) {
        PageHelper.clearPage();
        VQMSVisitRecordYuchai visitRecordYuchai = visitRecordYuchaiService.getYuchaiAccess(vqmsVisitRecordYuchai);
        if (visitRecordYuchai == null) {
            return AjaxResult.success("301","未找到南大门进场记录");
        } else {
            //同步玉驰记录
            if (visitRecordYuchai.getReservationId() != null){
                //查询同一个预约ID的玉驰访客记录
                VQMSVisitRecordYuchi visitRecordYuchi = visitRecordYuchiService.getReservationId(visitRecordYuchai.getReservationId());
                if (visitRecordYuchi != null) {
                    visitRecordYuchi.setFactoryTime(new Date());
                    int n = visitRecordYuchiService.update(visitRecordYuchi);
                    if (n != 1) {
                        logger.error("司机扫码离场-同步玉驰出厂时间失败");
                    }
                } else {
                    logger.error("司机扫码离场-未找到玉驰对应预约ID访客记录：" + visitRecordYuchai.getReservationId());
                }
            }
            //更新最新一条记录出厂时间
            visitRecordYuchai.setFactoryTime(new Date());
            int i = visitRecordYuchaiService.update(visitRecordYuchai);
            return AjaxResult.success("200","南大门出厂登记成功");
        }
    }

    /**
     * 司机出厂登记(预约记录确认)
     *
     * @param vqmsVisitRecordYuchai
     * @return
     */
    @Log(title = "司机出厂登记(玉驰)", businessType = BusinessType.INSERT)
    @PostMapping("/idConfirm")
    public AjaxResult idConfirm(@RequestBody VQMSVisitRecordYuchai vqmsVisitRecordYuchai) {
        VQMSVisitRecordYuchai visitRecordYuchai = visitRecordYuchaiService.getById(vqmsVisitRecordYuchai.getId());
        if (visitRecordYuchai == null) {
            return AjaxResult.error("未找到进厂登记记录");
        }
        if (visitRecordYuchai.getReservationId() != null) {      //预约ID不为空
            //查询同一个预约ID的玉驰访客记录
            VQMSVisitRecordYuchi visitRecordYuchi = visitRecordYuchiService.getReservationId(visitRecordYuchai.getReservationId());
            if (visitRecordYuchi != null) {
                visitRecordYuchi.setFactoryTime(new Date());
                int n = visitRecordYuchiService.update(visitRecordYuchi);
                if (n != 1) {
                    logger.error("司机确认离场-同步玉驰出厂时间失败");
                }
            } else {
                logger.error("司机确认离场-未找到玉驰对应预约ID访客记录：" + visitRecordYuchai.getReservationId());
            }

//            if ()
        }
        //更新最新一条记录出厂时间
        visitRecordYuchai.setFactoryTime(new Date());
        int i = visitRecordYuchaiService.update(visitRecordYuchai);
        return AjaxResult.success();

    }


    /**
     * 根据手机号码查询访客最新一条记录
     * @param vqmsVisitRecordYuchai
     * @return
     */
    @RequestMapping("/getLatest")
    public AjaxResult getLatest(VQMSVisitRecordYuchai vqmsVisitRecordYuchai){
        List<VQMSVisitRecordYuchai> list = visitRecordYuchaiService.getLatestCreateTime(vqmsVisitRecordYuchai);
        if (list.isEmpty()){
            return AjaxResult.success("201",list);
        }
        return AjaxResult.success("200",list.get(0));
    }


}
